import {Card, Breadcrumb, Form, Button, Radio, DatePicker, Select, Table, Tag, Space, message, Popconfirm} from 'antd'
import img404 from '@/assets/error.png'
// 引入时间选择器汉化包
import locale from 'antd/es/date-picker/locale/zh_CN'
import {FireOutlined, HomeOutlined, UserOutlined, EditOutlined, DeleteOutlined} from "@ant-design/icons";
import React, {useEffect, useState} from "react";
import useChannels from "@/hooks/useChannels";
import {useNavigate} from "react-router-dom";
import useArticleList from "@/hooks/useArticleList";
import {deleteArticleAPI} from "@/apis";

const {Option} = Select
const {RangePicker} = DatePicker
const Article = () => {
    const navigate = useNavigate()
    const [onLoading, setLoading] = useState(false)
    // 获取频道数据
    const {channelList} = useChannels()

    // 筛选表单提交
    // 1. 准备参数
    const [reqData, setReqData] = useState({
        status: '',
        channel_id: '',
        begin_pubdate: '',
        end_pubdate: '',
        page: 1,
        per_page: 5
    })
    // 2. 获取筛选参数
    const onFinish = async (formValues) => {
        // console.log(formValues)
        // 把表单的值赋值给reqData
        setLoading(true)
        await setReqData({
            ...reqData,
            channel_id: formValues.channel_id,
            status: formValues.status,
            begin_pubdate: formValues.date[0].format('YYYY-MM-DD'),
            end_pubdate: formValues.date[1].format('YYYY-MM-DD')
        })
        // 3. 重新拉取数据列表 + 渲染table逻辑复用
        // 监听reqData变化 重复执行依赖函数
        if (formValues) {
            message.success('查询成功')
        }
    }

    // 声明文章列表数据和更改状态
    const {articleList, count} = useArticleList(reqData)
    useEffect(() => {
        setLoading(false)
    }, [articleList]);
    // 准备列数据
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            width: 120,
            render: cover => {
                return <img src={cover.images[0] || img404} width={80} height={60} alt=""/>
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 220
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: data => data === 2 ? <Tag color="success">审核通过</Tag> : <Tag color="warning">待审核</Tag>
        },
        {
            title: '发布时间',
            dataIndex: 'pubdate'
        },
        {
            title: '阅读数',
            dataIndex: 'read_count'
        },
        {
            title: '评论数',
            dataIndex: 'comment_count'
        },
        {
            title: '点赞数',
            dataIndex: 'like_count'
        },
        {
            title: '操作',
            render: data => {
                return (
                    <Space size="middle">
                        <Popconfirm
                            title="更新列表信息"
                            description="你确定要更新这条数据吗？"
                            onConfirm={() => onEdit(data)}
                            okText="Yes"
                            cancelText="No">
                            <Button type="primary" shape="circle" icon={<EditOutlined/>}/>
                        </Popconfirm>
                        <Popconfirm
                            title="删除列表信息"
                            description="你确定要删除这条数据吗？"
                            onConfirm={() => onDelete(data)}
                            okText="Yes"
                            cancelText="No">
                            <Button
                                type="primary"
                                danger
                                shape="circle"
                                icon={<DeleteOutlined/>}
                            />
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ]

    // 分页函数
    const onPageChange = (page) => {
        // console.log(page)
        setLoading(true)
        setReqData(
            {
                ...reqData,
                // 改变页码 发送请求 重新渲染table
                page: page
            }
        )
    }

    //  删除数据操作
    const onDelete = (data) => {
        async function deleteArticle() {
            setLoading(true)
            const res = await deleteArticleAPI(data.id)
            // 重新拉取数据列表 + 渲染table逻辑复用
            setReqData({
                ...reqData,
                page: 1
            })
            if (res.message === 'OK') {
                message.success('删除成功')
            } else {
                message.error('删除失败')
            }
        }

        deleteArticle()
    }

    // 编辑文章详情 + 跳转
    const onEdit = (data) => {
        // 跳转到编辑页面
        // 拼接路由
        navigate(`/publish?id=${data.id}`)
    }
    return (
        <div>
            {/*文章筛选区域*/}
            <Card
                title={
                    <Breadcrumb
                        items={[
                            {
                                href: '/',
                                title: (
                                    <>
                                        <HomeOutlined/>
                                        <span>首页</span>
                                    </>
                                ),
                            },
                            {
                                href: '/publish',
                                title: (
                                    <>
                                        <EditOutlined/>
                                        <span>创建文章</span>
                                    </>
                                ),
                            },
                            {
                                href: '/hot',
                                title: (
                                    <>
                                        <FireOutlined/>
                                        <span>时讯热点</span>
                                    </>
                                ),
                            },
                            {
                                href: '/user',
                                title: (
                                    <>
                                        <UserOutlined/>
                                        <span>个人中心</span>
                                    </>
                                ),
                            }
                        ]}/>
                }
                style={{marginBottom: 20, height: 300}}>
                <Form initialValues={{status: ''}} onFinish={onFinish} validateTrigger="onBlur">
                    <Form.Item label="状态" name="status">
                        <Radio.Group>
                            <Radio value={''}>全部</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>审核通过</Radio>
                            <Radio value={3}>草稿箱</Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="频道" name="channel_id"
                               rules={[{
                                   required: true,
                                   message: '请选择文章频道'
                               }]}>
                        <Select
                            placeholder="请选择文章频道"
                            style={{width: 180}}>
                            {channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
                        </Select>
                    </Form.Item>

                    <Form.Item label="日期" name="date"
                               rules={[{
                                   required: true,
                                   message: '请选择时间区间'
                               }]}>
                        {/* 传入locale属性 控制中文显示*/}
                        <RangePicker locale={locale}></RangePicker>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{marginLeft: 40, width: 120}}>
                            查询
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            {/*表格列表区域*/}
            <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
                <Table rowKey="id" loading={onLoading} columns={columns} dataSource={articleList} pagination={{
                    total: count,
                    pageSize: reqData.per_page,
                    onChange: onPageChange
                }}/>
            </Card>
        </div>
    )
}

export default Article